﻿using System;
using System.Collections.Generic;
using System.Data;
using TidyBlog.Entity;
using TidyBlog.Data;

namespace TidyBlog.DAL
{
	/// <summary>
	/// 评论数据访问层
	/// </summary>
	public class CommentDAL
	{
		/// <summary>
        /// 创建评论记录
        /// </summary>
        /// <param name="comment">评论</param>
        /// <returns>影响的行数</returns>
        public static int Create(Comment comment)
        {
            return SimpleORM<Comment>.Insert(comment);
        }
        
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="commentIds">评论编号，多个编号用英文逗号隔开</param>
        /// <returns>影响的记录数</returns>
        public static int Delete(string commentIds)
        {
            return DbHelper.ExecuteNonQuery(
                DbHelper.CreateCommand((new DeleteCommand(SimpleORM<Comment>.TableName))
                    .Where(new WhereCondition("CommentId", "(" + commentIds + ")")
                    {
                        Operator = WhereOperator.IN
                    })
                    .ToString()
                )
            );
        }
        
        /// <summary>
        /// 审核评论
        /// </summary>
        /// <param name="commentIds">评论编号，多个编号用英文逗号隔开</param>
        /// <returns>影响的记录数</returns>
        public static int Review(string commentIds)
        {
            return DbHelper.ExecuteNonQuery(
                DbHelper.CreateCommand((new UpdateCommand(SimpleORM<Comment>.TableName))
                    .Set(new[]
                    {
                        new ColumnValuePair("Visibility", "1")
                    })
                    .Where(new WhereCondition("CommentId", "(" + commentIds + ")")
                    {
                        Operator = WhereOperator.IN
                    })
                    .ToString()
                )
            );
        }

        /// <summary>
        /// 读取评论列表
        /// </summary>
        /// <param name="queryParams">查询参数</param>
        /// <param name="isAsc">排序方式，true为按发表时间升序排列，false为按发表时间降序排列</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="currentPage">当前页</param>
        /// <returns>评论列表</returns>
        public static DataPaging<Comment> List(Dictionary<string, string> queryParams, bool isAsc, ushort pageSize, int currentPage)
        {
            PagingHelper<Comment> pagingHelper = DbHelper.Provider.CreatePagingHelper<Comment>();
            var whereConditions = new List<WhereCondition>();

            if (queryParams != null)
            {
                if (queryParams.ContainsKey("visibility"))
                {
                    whereConditions.Add(new WhereCondition("Visibility"));
                    SimpleORM<Comment>.AttachParam(pagingHelper.Cmd, "Visibility", queryParams["visibility"]);
                }
                if (queryParams.ContainsKey("articleid"))
                {
                    whereConditions.Add(new WhereCondition("ArticleId"));
                    SimpleORM<Comment>.AttachParam(pagingHelper.Cmd, "ArticleId", queryParams["articleid"]);
                }
            }

            pagingHelper.SQLCommand.OrderBy(new SortColumn()
            {
                Column = "CommentId",
                OrderWay = isAsc ? OrderWay.ASC : OrderWay.DESC
            }).Where(whereConditions);

            return pagingHelper.Execute(pageSize, currentPage);
        }

        /// <summary>
        /// 获取未审核评论数
        /// </summary>
        /// <returns>未审核评论数</returns>
        public static uint GetUnreviewedCount()
        {
            return Convert.ToUInt32(DbHelper.ExecuteScalar(
                DbHelper.CreateCommand((new SelectCommand(SimpleORM<Comment>.TableName))
                    .Select("COUNT(*)")
                    .Where(new WhereCondition("Visibility", "0"))
                    .ToString()
                )
            ));
        }

        /// <summary>
        /// 获取是否存在指定时间之后来自指定IP的评论
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="lastPostTime">发表时间</param>
        /// <returns>是否存在指定评论</returns>
        public static bool IsExists(string ip, DateTime lastPostTime)
        {
            var cmd = DbHelper.CreateCommand((new SelectCommand(SimpleORM<Comment>.TableName))
                .Select("COUNT(*)")
                .Where(new[]
                {
                    new WhereCondition("IP"),
                    new WhereCondition("PostTime")
                    {
                        Operator = WhereOperator.GREATER
                    }
                })
                .ToString()
            );

            SimpleORM<Comment>.AttachParam(cmd, "IP", ip);
            SimpleORM<Comment>.AttachParam(cmd, "PostTime", lastPostTime);

            return Convert.ToUInt32(DbHelper.ExecuteScalar(cmd)) > 0;
        }
	}
}
